package com.gistone.commis.api.restController;

import com.gistone.commis.constant.Status;
import com.gistone.commis.dto.*;
import com.gistone.commis.entity.*;
import com.gistone.commis.mapper.CommunityMapper;
import com.gistone.commis.mapper.DepartMapper;
import com.gistone.commis.mapper.HouseLogMapper;
import com.gistone.commis.mapper.HouseMapper;
import com.gistone.commis.query.QueryHouse;
import com.gistone.commis.util.DataTablePageUtil;
import com.gistone.commis.util.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * Created by wangfan on 2017/5/5.
 */
@RestController("apiHouseController")
@RequestMapping("api/house")
public class HouseController {

    private static final Logger logger = LoggerFactory.getLogger(HouseController.class);


    @Autowired
    private HouseMapper houseMapper;

    @Autowired
    private CommunityMapper communityMapper;

    @Autowired
    private DepartMapper departMapper;

    @Autowired
    private HouseLogMapper houseLogMapper;

    /**
     * 根据id获取房屋信息
     *
     * @param id
     * @return
     */

    @RequestMapping(method = RequestMethod.GET, value = "/{id}")
    public House house(@PathVariable int id) {
        House house = houseMapper.selectByPrimaryKey(id);
        return house;
    }


    /**
     * 获取所有房屋信息
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/all")
    public List<House> loadAll() {
        return this.houseMapper.findHouses();
    }


    /**
     * 新建房屋信息
     *
     * @param request
     * @param response
     * @return
     */
    @Transactional
    @RequestMapping(method = RequestMethod.POST, value = "/create")
    public Object create(HttpServletRequest request, HttpServletResponse response, Integer id) {

        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("userInfo");

        House house = new House();
        house.setUserId(user.getUserId());
        EditorResult<House> houseEditorResult = new EditorResult<>();

        List<FieldError> fieldErrorList = new ArrayList<>();
//        house.setHouseId(houseId);

        getHouse(request, "data[0][", house, fieldErrorList);
        house.setRegisterTime(new Date());
        if (null == house.getCommunityId()) {
            house.setCommunityId(user.getCommunity().getCommunityId());
        }
        if (null == house.getDepartId()) {
            house.setDepartId(1);
        }


//        System.out.println(houseId);

        if (fieldErrorList.size() > 0) {
            logger.error("字段格式错误");
            houseEditorResult.setFieldErrors(fieldErrorList);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return houseEditorResult;
        }
        if (houseMapper.insertSelective(house) > 0) {
            logger.info("houseId--" + house.getHouseId());
            List<House> data = new ArrayList<>();
            data.add(house);
            houseEditorResult.setData(data);
//            house.setHouseId(houseId);
            HouseLog houseLog = new HouseLog(house, new Date(), user.getUserId());

            if (houseLogMapper.insertSelective(houseLog) > 0) {
                logger.info("保存住房日志信息成功");
            } else {
                logger.info("保存住房日志信息失败");
                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);

            }
        } else {
            response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }


        return houseEditorResult;
//
    }

    /**
     * 批量修改房屋信息， id以,号分割
     *
     * @param houseIdStr
     * @param request
     * @return
     */

    @Transactional
    @RequestMapping(method = RequestMethod.PUT, value = "/edit")
    public Object edit(@RequestParam("id") String houseIdStr, HttpServletRequest request, HttpServletResponse response) {

        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("userInfo");
        String[] arr = houseIdStr.split(",");
        EditorResult<House> houseEditorResult = new EditorResult<>();
        List<House> data = new ArrayList<>();

        for (int i = 0; i < arr.length; i++) {
            int houseId = Integer.valueOf(arr[i]);
            House house = new House();
            house.setHouseId(houseId);
            List<FieldError> fieldErrorList = new ArrayList<>();
            getHouse(request, "data[" + houseId + "][", house, fieldErrorList);
//            house = getDotHouse(request, "data." + houseId + ".", house);
            if (fieldErrorList.size() > 0) {
                logger.error("字段错误");
                houseEditorResult.setFieldErrors(fieldErrorList);
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                return houseEditorResult;
            }
            if (houseMapper.updateByPrimaryKeySelective(house) > 0) {
                House h = houseMapper.selectByPrimaryKey(houseId);
                data.add(h);

                HouseLog houseLog = new HouseLog(h, new Date(), user.getUserId());

                if (houseLogMapper.insertSelective(houseLog) > 0) {
                    logger.info("保存住房日志信息成功");
                } else {
                    logger.info("保存住房日志信息失败");
                    response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);

                }


            } else {
                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }


        }
        houseEditorResult.setData(data);
        return houseEditorResult;


    }


    /**
     * 用房删除
     * 通过房屋ID批量删除房屋信息， id以,号分割
     *
     * @param houseIdStr
     * @param response
     * @return
     */
    @Transactional
    @RequestMapping(method = RequestMethod.DELETE, value = "/remove")
    public Object remove(@RequestParam("id") String houseIdStr, HttpServletResponse response) {
        String[] arr = houseIdStr.split(",");
        EditorResult<House> houseEditorResult = new EditorResult<>();
        for (int i = 0; i < arr.length; i++) {
            int houseId = Integer.valueOf(arr[i]);
            House house = new House();
            house.setHouseId(houseId);
            house.setIsDelete(1);
            if (houseMapper.updateByPrimaryKeySelective(house) > 0) {
                System.out.println("删除" + houseId + "成功！");


            } else {
                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }
        }
        return houseEditorResult;


    }

    /**
     * dataTables 表单数据返回
     *
     * @param request
     * @return
     */

    @Transactional
    @RequestMapping(method = RequestMethod.GET, value = "/pageDatatables")
    public DataTablePageUtil<House> pageDatatables(HttpServletRequest request, QueryHouse house) {
/*        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("userInfo");
        logger.info("用户信息：" + user.toString());
        int community_id = user.getCommunity().getCommunityId();
        house.setCommunityId(community_id);*/

        List<Community> communities = communityMapper.findCommunitys();
        Options os = new Options();
        List<Option> optionList = new ArrayList<>();
        for (Community community : communities) {

            Option option = new Option();
            option.setLabel(community.getCommunityName());
            option.setValue(community.getCommunityId());
            optionList.add(option);


        }
        os.setCommunityId(optionList);
        List<Depart> departs = departMapper.findDeparts();
        optionList = new ArrayList<>();
        for (Depart depart : departs) {

            Option option = new Option();
            option.setLabel(depart.getDepartName());
            option.setValue(depart.getDepartId());
            optionList.add(option);


        }

        os.setDepartId(optionList);


        DataTablePageUtil<House> dataTable = new DataTablePageUtil<>(request);
        house.setIsDelete(0);
        PageHelper.startPage(dataTable.getPage_num(), dataTable.getPage_size());
        List<House> list = houseMapper.selectSelective(house);
        PageInfo<House> pageInfo = new PageInfo<>(list);

        System.out.println(list.size());
        dataTable.setDraw(dataTable.getDraw());
        dataTable.setData(pageInfo.getList());
        dataTable.setOptions(os);
        dataTable.setRecordsTotal((int) pageInfo.getTotal());
        dataTable.setRecordsFiltered(dataTable.getRecordsTotal());
        //返回数据到页面


        return dataTable;

    }


    @Transactional
    @RequestMapping(method = RequestMethod.GET, value = "/sumArea")
    public Result sumArea(HttpServletRequest request, QueryHouse house) {

        house.setIsDelete(0);
        double sum;
        try {
            sum = houseMapper.sumSelective(house);
        } catch (Exception e) {
            sum = 0.0;
//          return new Result(Status.ERROR,"失败","");
        }


        return new Result(Status.SUCCESS, "失败", sum);

    }


    private void getHouse(HttpServletRequest request, String prefix, House house, List<FieldError> fieldErrorList) {
        System.out.println("-----");
        if (null != request.getParameter(prefix + "communityId]") && !request.getParameter(prefix + "communityId]").isEmpty()) {
            house.setCommunityId(Integer.valueOf(request.getParameter(prefix + "communityId]")));


        }
        if (null != request.getParameter(prefix + "departId]") && !request.getParameter(prefix + "departId]").isEmpty()) {
            house.setDepartId(Integer.valueOf(request.getParameter(prefix + "departId]")));


        }
        house.setHouseName(request.getParameter(prefix + "houseName]"));
        house.setHouseAdd(request.getParameter(prefix + "houseAdd]"));
        String acquireWay = request.getParameter(prefix + "acquireWay]");
        house.setAcquireWay(acquireWay);
        if (acquireWay.equals("2")) {
            if (null != request.getParameter(prefix + "buyDate]") && !request.getParameter(prefix + "buyDate]").isEmpty()) {
                try {
                    house.setBuyDate(DateUtil.StrToDate1(request.getParameter(prefix + "buyDate]")));
                } catch (Exception e) {
                    logger.error("时间格式不正确，必须为YYYY-MM-DD");
                    FieldError fieldError = new FieldError("buyDate", "时间格式不正确，必须为YYYY-MM-DD时间格式不正确，必须为YYYY-MM-DD");
                    fieldErrorList.add(fieldError);
                }
            }
            try {
                house.setMoney(Double.valueOf(request.getParameter(prefix + "money]")));
            } catch (NumberFormatException e) {
                logger.error("格式不正确，必须为Double数字");
                FieldError fieldError = new FieldError("money", "必须为Double数字");
                fieldErrorList.add(fieldError);
            }


        } else if (acquireWay.equals("4")) {
            house.setBuyDate(null);
            try {
                house.setMoney(Double.valueOf(request.getParameter(prefix + "money]")));
            } catch (NumberFormatException e) {
                logger.error("格式不正确，必须为Double数字");
                FieldError fieldError = new FieldError("money", "必须为Double数字");
                fieldErrorList.add(fieldError);
            }
        } else {


            house.setBuyDate(null);
            house.setMoney(null);
        }

        house.setFundFrom(request.getParameter(prefix + "fundFrom]"));
        if (null != request.getParameter(prefix + "completedTime]") && !request.getParameter(prefix + "completedTime]").isEmpty()) {

            System.out.println("-----" + request.getParameter(prefix + "completedTime]"));


            try {
                house.setCompletedTime(DateUtil.StrToDate1(request.getParameter(prefix + "completedTime]")));
            } catch (Exception e) {
                logger.error("时间格式不正确，必须为YYYY-MM-DD");
                FieldError fieldError = new FieldError("completedTime", "时间格式不正确，必须为YYYY-MM-DD时间格式不正确，必须为YYYY-MM-DD");
                fieldErrorList.add(fieldError);
            }
        } else {
            house.setCompletedTime(null);
        }
        house.setServiceCondition(request.getParameter(prefix + "serviceCondition]"));

//        house.setRegisterTime(DateUtil.StrToDate1(request.getParameter(prefix + "registerTime]")));
        try {
            house.setHouseArea(Double.valueOf(request.getParameter(prefix + "houseArea]")));
        } catch (NumberFormatException e) {
            logger.error("面积格式不正确，必须为double型");
            FieldError fieldError = new FieldError("houseArea", "面积格式不正确，必须为double型");
            fieldErrorList.add(fieldError);
        }
//        house.setHouseType(request.getParameter(prefix + "houseType]"));
        house.setRemarks(request.getParameter(prefix + "remarks]"));


    }

}
